package com.jerry.shop.controller;

import com.jerry.shop.bean.Category;
import com.jerry.shop.bean.Product;
import com.jerry.shop.converter.ProductConverter;
import com.jerry.shop.service.CategoryService;
import com.jerry.shop.service.ProductService;
import com.jerry.shop.utils.ResultVoUtil;
import com.jerry.shop.vo.CategoryVo;
import com.jerry.shop.vo.ProductVo;
import com.jerry.shop.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品控制器
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public ResultVo list() {

        //1. 查询所有的上架商品
        List<Product> productList = productService.findUpAll();

        //2. 查询所有上架商品的类目(一次性查询)
        List<Category> categoryList = findUpCategoryList(productList);

        //3. 数据拼装
        List<CategoryVo> categoryVoList = assembleCategoryVoList(productList, categoryList);

        return ResultVoUtil.success(categoryVoList);
    }

    public List<Category> findUpCategoryList(List<Product> productList) {
        //方法一：传统方法
//        List<Integer> categoryTypeList = new ArrayList<>();
//        for (Product product : productList) {
//            categoryTypeList.add(product.getCategoryType());
//        }
        //方法二：精简方法(java8, lambda)
        List<Integer> categoryTypeList = productList.stream()
                .map(e -> e.getCategoryType())
                .collect(Collectors.toList());
        List<Category> categoryList = categoryService.findByCategoryTypeIn(categoryTypeList);
        return categoryList;
    }

    public List<CategoryVo> assembleCategoryVoList(List<Product> productList, List<Category> categoryList) {
        List<CategoryVo> categoryVoList = new ArrayList<>();
        for (Category category: categoryList) {
            //类目
            CategoryVo categoryVo = new CategoryVo();
            categoryVo.setCategoryType(category.getType());
            categoryVo.setCategoryName(category.getName());
            //商品列表
            List<ProductVo> productVoList = new ArrayList<>();
            for (Product product: productList) {
                if (product.getCategoryType().equals(category.getType())) {
                    productVoList.add(ProductConverter.convert(product));
                }
            }
            //商品列表加入类目中
            categoryVo.setProductVoList(productVoList);
            categoryVoList.add(categoryVo);
        }
        return categoryVoList;
    }

}
